<?php
/**
 * 公共函数-系统函数
 * User: dxk
 * Date: 2020-07-17
 */

use Carbon\Carbon;
use JetBrains\PhpStorm\NoReturn;

function get_envname(): string
{
    if (is_local())
        $env_name = '本地环境';
    elseif (is_test())
        $env_name = '测试环境';
    elseif (is_pre())
        $env_name = '预发环境';
    elseif (is_online())
        $env_name = '生产环境';
    else
        $env_name = '未知环境';
    return $env_name;
}

/**
 * 是否生产环境
 * @return bool
 */
function is_online(): bool
{
    return App::environment() == 'online';
}

/**
 * 是否预发环境
 * @return bool
 */
function is_pre(): bool
{
    return App::environment() == 'pre';
}

/**
 * 是否本地环境
 * @return bool
 */
function is_local(): bool
{
    return App::environment() == 'local';
}

/**
 * 是否测试环境
 * @return bool
 */
function is_test(): bool
{
    return App::environment() == 'test';
}

/**
 * 获取设备信息
 * @return string
 */
function easy_device(): string
{
    return easy_ip() . ' ' . Agent::platform() . ' ' . Agent::version(Agent::platform()) . ' ' . Agent::device() . ' ' . Agent::browser() . ' ' . Agent::version(Agent::browser());
}

function easy_device_id(): string
{
    $HTTP_USER_AGENT = getenv('HTTP_USER_AGENT');
    preg_match('/[^(]*[(]([^\)]*)[\)]/', $HTTP_USER_AGENT, $match);
    $os = $match[1] ?? '';
    if (getenv('USERDOMAIN')) {
        $os .= '; ' . getenv('USERDOMAIN');
    }
    return $os;
}

/**
 * xss注入过滤
 * @param $val
 * @return array|bool|float|int|string|null
 */
function easy_clean_xss($val): float|array|bool|int|string|null
{
    if (empty($val) || is_int($val) || is_bool($val) || is_numeric($val)) return $val;
    if (is_string($val)) {
        $val_arr = json_decode($val, true);
        if (is_array($val_arr)) {
            return $val;
        }
    }
    if (is_array($val)) {
        foreach ($val as $k => $v) {
            $val[$k] = easy_clean_xss($v);
        }
        return $val;
    }
    return htmlspecialchars($val, ENT_QUOTES, 'utf-8');
}

/**
 * 清理富文本xss注入
 * @param $html
 * @return string
 */
function easy_clean_html($html): string
{
    $config = HTMLPurifier_Config::createDefault();
    $config->set('Cache.SerializerPath', storage_path('PurifierCache'));
    $purifier = new HTMLPurifier();
    return $purifier->purify($html);
}

/**
 * 转换富文本编辑器内容为可存储内容
 * @param $html
 * @param bool $clean_xss
 * @return string|string[]
 */
function easy_convert_html_to_store($html, bool $clean_xss = true): array|string
{
    if ($clean_xss) {
        $html = easy_clean_html($html);
    }
    $search = [easy_url('')];
    return str_ireplace($search, '[ATTACHE_URL]', $html);
}

/**
 * 转换富文本编辑器内容为可访问内容
 * @param $html
 * @param null $force_secure
 * @return string|string[]
 */
function convert_store_to_html($html, $force_secure = null): array|string
{
    if ($force_secure == null) {
        if (request()->getScheme() == 'https' || (key_exists('HTTP_X_FORWARDED_PROTO', $_SERVER) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO'])) == 'https') {
            $force_secure = true;
        } else {
            $force_secure = false;
        }
    }
    $attach_url = easy_url('', [], $force_secure) . '/';
    return str_ireplace('[ATTACHE_URL]', $attach_url, $html);
}

/**
 * 加载js
 * @param array|string $resource
 * @return string
 */
function easy_js(array|string $resource): string
{
    return \App\Library\Service\EasyJs::usejs($resource);
}

/**
 * 加载js
 * @param array|string $resource
 * @return string
 */
function easy_css(array|string $resource): string
{
    return \App\Library\Service\EasyJs::usecss($resource);
}

/**
 * 静态资源路径
 * @param string $path
 * @param boolean|null $force_secure 是否强制https
 * @return string
 */
function easy_asset(string $path, bool $force_secure = null): string
{
    if ($force_secure == null) {
        if (request()->getScheme() == 'https' || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https')) {
            $force_secure = true;
        } else {
            $force_secure = false;
        }
    }
    $static_file_path = config('sys.static_file_path');
    if (!empty($static_file_path)) {
        $ssl_static_file_path = config('sys.ssl_static_file_path');
        if (!empty($ssl_static_file_path) && $force_secure) {
            $path = $ssl_static_file_path . $path;

        } else {
            $path = $static_file_path . $path;
        }
    } else {
        $path = 'resource/' . $path;
        $path = asset($path, $force_secure);
    }
    return $path;
}

/**
 * 生成带参数的链接地址
 * @param string $url
 * @param array $param
 * @param bool|null $secure
 * @return string
 */
function easy_url_hash(string $url, array $param = [], bool $secure = null): string
{
    $url = url($url, '', $secure);
    $param_str = '';
    foreach ($param as $k => $v) {
        if (is_array($v)) {
            foreach ($v as $v2) {
                if ($v2 !== '') {
                    $param_str .= '&' . $k . '[]=' . $v2;
                }
            }

        } else {
            if ($v !== '') {
                $param_str .= '&' . $k . '=' . $v;
            }
        }
    }
    $param_str = trim($param_str, '&');
    if (empty($param_str)) {
        return $url;
    }
    if (!str_contains($url, '?')) {
        $url .= '?' . $param_str;
    } else {
        $url .= '&' . $param_str;
    }
    if (!str_contains($url, '#')) {
        $url .= '#' . $param_str;
    } else {
        $url .= '&' . $param_str;
    }
    return $url;
}

/**
 * 生成带参数的链接地址
 * @param string $url
 * @param array $param
 * @param bool|null $secure
 * @return string
 */
function easy_url(string $url, array $param = [], bool $secure = null): string
{
    $url = url($url, '', $secure);
    $param_str = '';
    foreach ($param as $k => $v) {
        if (is_array($v)) {
            foreach ($v as $v2) {
                if ($v2 !== '') {
                    $param_str .= '&' . $k . '[]=' . $v2;
                }
            }

        } else {
            if ($v !== '') {
                $param_str .= '&' . $k . '=' . $v;
            }
        }
    }
    $param_str = trim($param_str, '&');
    if (empty($param_str)) {
        return $url;
    }
    if (!str_contains($url, '?')) {
        $url .= '?' . $param_str;
    } else {
        $url .= '&' . $param_str;
    }
    return $url;
}

/**
 * 上传文件网络访问路径
 * @param string $path
 * @param string $size
 * @param bool|null $force_secure
 * @return string
 */
function easy_attached(string $path = '', string $size = '', bool $force_secure = null): string
{
    if ($force_secure == null) {
        if (request()->getScheme() == 'https' || strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https') {
            $force_secure = true;
        } else {
            $force_secure = false;
        }
    }
    if (empty($path)) {
        return '';
    }
    $path = str_ireplace('\\', '/', $path);
    if (str_starts_with($path, "http")) {
        return $path;
    }
    //文件存在，判断是否配置了上传文件路径（CDN用）
    $upload_path = config('sys.upload_path');
    if (!empty($upload_path)) {
        $ssl_upload_path = config('sys.ssl_upload_path');
        if (!empty($ssl_upload_path) && $force_secure) {
            $pic_path = $ssl_upload_path . $path;

        } else {
            $pic_path = $upload_path . $path;
        }
    } else {
        $path = 'attached/' . $path;
        $pic_path = asset($path, $force_secure);
    }
    $size = trim($size);
    if (!empty($size)) {
        $size_list = config('sys.pic_size');
        if (in_array($size, $size_list)) {
            $pic_path = $pic_path . '_' . $size . '.jpg';
        }
    }
    return $pic_path;
}

/**
 * attached存储路径
 * @param string $path
 * @return string
 */
function easy_attached_path(string $path = ''): string
{
    $path = 'attached' . DIRECTORY_SEPARATOR . $path;
    return public_path($path);
}

/**
 * 删除云空间文件
 * @param string $path
 * @return array
 */
function easy_cloud_delete(string $path): array
{
    $path = str_ireplace('\\', '/', $path);
    return (new \App\Library\Service\AliCloud\OSS())->deleteFile($path);
}

/**
 * 文件云空间路径
 * @param string $path
 * @param string $size
 * @return string
 * @throws Exception
 */
function easy_cloud_attached(string $path, string $size = ''): string
{
    if (empty($path)) {
        return '';
    }
    $path = str_ireplace('\\', '/', $path);
    //文件存在，判断是否配置了上传文件路径（CDN用）
    $pic_path = (new \App\Library\Service\AliCloud\OSS())->getFilePath($path);
    $size = trim($size);
    if (!empty($size)) {
        $size_list = config('sys.pic_size');
        if (in_array($size, $size_list)) {
            $pic_path = $pic_path . '?x-oss-process=style/' . $size;
        }
    }
    return $pic_path;
}

/**
 * 没有权限
 */
#[NoReturn] function easy_nopriv()
{
    $tip = '抱歉! 你没有此功能的操作权限，请联系系统管理员！';
    if (request()->ajax()) {
        echo json_encode(alert_info(500, $tip));
    }
    echo view('errors.nopriv', ['tip' => $tip]);
    exit;
}


/**
 * 过滤请求参数
 * @param array $filter
 * @return string
 */
function easy_filter_request_param(array $filter = []): string
{
    $query = request()->query();
    $params = [];
    foreach ($query as $key => $item) {
        if (!in_array($key, $filter)) {
            $params[$key] = $item;
        }
    }
    return request()->url() . '?' . http_build_query($params);
}

/**
 * 记录文本日志
 * @param string $dirname
 * @param mixed $contents
 * @param string $sub_txt_name
 * @return bool
 */
function easy_log(string $dirname, mixed $contents, string $sub_txt_name = ''): bool
{
    $dirname = str_ireplace(['/', '\\'], DIRECTORY_SEPARATOR, $dirname);
    $dirname = str_ireplace(['.', ':', '*', '?', '<', '>', '"', "'", '|', ' '], '', $dirname);
    $sub_txt_name = str_ireplace(['.', ':', '*', '?', '<', '>', '"', "'", '|', ' ', '/', '\\'], '', $sub_txt_name);
    $log_path = public_path('attached' . DIRECTORY_SEPARATOR . 'log') . DIRECTORY_SEPARATOR . $dirname . DIRECTORY_SEPARATOR . date('Ym') . DIRECTORY_SEPARATOR;
    if (!file_exists($log_path)) {
        easy_mk_dir($log_path);
    }
    if (!empty($sub_txt_name)) {
        $file_name = date('Ymd') . '-' . $sub_txt_name . '.log';
    } else {
        $file_name = date('Ymd') . '.log';
    }
    $file = $log_path . $file_name;
    $handle = fopen($file, 'a+');
    @chmod($file, 0777);
    fwrite($handle, Carbon::now()->toDateTimeString('m') . '    ' . json_encode($contents, JSON_UNESCAPED_UNICODE) . PHP_EOL . PHP_EOL);
    fclose($handle);
    return true;
}

/**
 * 记录文本日志
 * @param string $dirname
 * @param mixed $contents
 * @param string $sub_txt_name 子文件名称，一般为merchant_id方便区分企业
 * @return bool
 */
function easy_artisan_log(string $dirname, mixed $contents, string $sub_txt_name = '')
{
    $dir = realpath(dirname(__FILE__) . DIRECTORY_SEPARATOR . '../../..')
        . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'attached' . DIRECTORY_SEPARATOR . 'artisan_log';
    $dirname = str_ireplace(['/', '\\'], DIRECTORY_SEPARATOR, $dirname);
    $dirname = str_ireplace(['.', ':', '*', '?', '<', '>', '"', "'", '|', ' '], '', $dirname);
    $sub_txt_name = str_ireplace(['.', ':', '*', '?', '<', '>', '"', "'", '|', ' ', '/', '\\'], '', $sub_txt_name);
    $log_path = $dir . DIRECTORY_SEPARATOR . $dirname . DIRECTORY_SEPARATOR . date('Ym') . DIRECTORY_SEPARATOR;
    if (!file_exists($log_path)) {
        easy_mk_dir($log_path);
    }
    if (!empty($sub_txt_name)) {
        $file_name = date('Ymd') . '-' . $sub_txt_name . '.log';
    } else {
        $file_name = date('Ymd') . '.log';
    }
    $file = $log_path . $file_name;
    $handle = fopen($file, 'a+');
    @chmod($file, 0777);
    fwrite($handle, date('Y-m-d H:i:s') . '    ' . json_encode($contents, JSON_UNESCAPED_UNICODE) . PHP_EOL . PHP_EOL);
    fclose($handle);
    return true;
}


/**
 * 管理端检测角色权限
 * @param string $routes
 * @return bool
 */
function easy_admin_power(string $routes): bool
{
    return \App\Service\Core\Core\CoreMenuRolePowerService::isPowerRoutes(session_admin('group_id'), $routes);
}

/**
 * 管理端session
 * @param null $key
 * @param null $default
 * @return mixed
 */
function session_admin($key = null, $default = null): mixed
{
    $auth = session('core_auth');
    if (!is_array($auth)) $auth = [];
    if (is_null($key)) {
        return $auth;
    }
    return Arr::get($auth, $key, $default);
}

/**
 * 企业地址
 * @param string $url
 * @param array $param
 * @param null $secure
 * @return string
 */
function easy_wap_url(string $url, array $param = [], $secure = null): string
{
    return easy_url('wap/' . $url, $param, $secure);
}

/**
 * 公众号session
 * @param null $key
 * @param null $default
 * @return mixed
 */
function session_wap($key = null, $default = null): mixed
{
    $auth = session('wap_auth');
    if (!is_array($auth)) $auth = [];
    if (is_null($key)) {
        return $auth;
    }
    return Arr::get($auth, $key, $default);
}

/**
 * wap提示
 * @param string $msg
 * @param array $params
 */
#[NoReturn] function easy_wap_tip(string $msg, array $params = [])
{
    if (request()->ajax()) {
        echo json_encode(alert_info(1, $msg));
    } else {
        echo view('wap.layout.tip', compact('msg', 'params'));
    }
    exit;
}
